<template>
  <div class="clearfix">
    <a-upload
      :action="`${process.env.VUE_APP_API_BASE_URL}/api/upload/upload`"
      list-type="picture-card"
      :file-list="fileList"
      name="file"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < length">
        <a-icon type="plus" />
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default {
  props: {
    list: {
      type: [Array, null],
      default: () => []
    },
    length: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  created () {
    this.setList()
  },
  watch: {
    list () {
      this.setList()
    }
  },
  methods: {
    setList () {
      const { list } = this
      if (!list) return false
      const arr = []
      for (let i = 0; i < list.length; i++) {
        const name = list[i].split('/').pop()
        arr.push({
          uid: i + 100,
          status: 'done',
          name: name,
          url: process.env.VUE_APP_API_BASE_URL + list[i]
        })
      }
      this.fileList = arr
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
    },
    getPicList () {
      const res = []
      const { fileList } = this
      for (let i = 0; i < fileList.length; i++) {
        if (fileList[i].status === 'done') {
          if (fileList[i].url) {
            // 旧图片
            res.push(fileList[i].url.split(process.env.VUE_APP_API_BASE_URL)[1])
          } else {
            // 新图片
            if (fileList[i].response.code === 0) {
              res.push(fileList[i].response.data.url || '')
            }
          }
        }
      }
      return res
    },
    clear () {
      this.fileList = []
    }
  }
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
